<template>
  <div>
    <h3>我的活动总分：{{ totalPoints }}</h3>

    <div style="margin-top: 24px;">
      <h4>待签到/签退活动</h4>
      <el-table
        :data="unfinishedActivities"
        style="width: 100%; margin-bottom: 24px;"
        @row-click="handleUnfinishedRowClick"
      >
        <el-table-column prop="title" label="活动名称" />
        <el-table-column prop="orgId" label="组织ID" width="100" />
        <el-table-column prop="point" label="分数" width="80" />
        <el-table-column prop="startTime" label="开始时间" />
        <el-table-column prop="endTime" label="结束时间" />
        <el-table-column prop="location" label="地点" />
        <el-table-column prop="status" label="状态" width="100" />
      </el-table>
      <div v-if="unfinishedActivities.length === 0" style="color: #aaa; text-align: center;">暂无待签到/签退活动</div>
    </div>

    <div style="margin-top: 32px;">
      <h4>已完成活动</h4>
      <el-table
        :data="finishedActivities"
        style="width: 100%;"
        @row-click="handleFinishedRowClick"
      >
        <el-table-column prop="title" label="活动名称" />
        <el-table-column prop="orgId" label="组织ID" width="100" />
        <el-table-column prop="point" label="分数" width="80" />
        <el-table-column prop="startTime" label="开始时间" />
        <el-table-column prop="endTime" label="结束时间" />
        <el-table-column prop="location" label="地点" />
        <el-table-column prop="status" label="状态" width="100" />
      </el-table>
      <div v-if="finishedActivities.length === 0" style="color: #aaa; text-align: center;">暂无已完成活动</div>
    </div>

    <!-- 签到/签退弹窗 -->
    <el-dialog v-model="dialogVisible" title="活动签到/签退" width="480px" :close-on-click-modal="false">
      <div v-if="currentActivity">
        <div style="margin-bottom: 12px;"><b>活动名称：</b>{{ currentActivity.title }}</div>
        <div style="margin-bottom: 12px;"><b>内容：</b>{{ currentActivity.content }}</div>
        <div style="margin-bottom: 12px;"><b>地点：</b>{{ currentActivity.location }}</div>
        <div style="margin-bottom: 12px;"><b>时间：</b>{{ currentActivity.startTime }} ~ {{ currentActivity.endTime }}</div>
        <div style="margin-bottom: 12px;"><b>状态：</b>{{ currentActivity.status }}</div>
        <el-button type="success" @click="handleSignIn(currentActivity.actId)" style="margin-right: 16px;">签到</el-button>
        <el-button type="primary" @click="handleSignOut(currentActivity.actId)">签退</el-button>
      </div>
    </el-dialog>

    <!-- 评价弹窗 -->
    <el-dialog v-model="evaluateDialogVisible" title="活动评价" width="480px" :close-on-click-modal="false">
      <div v-if="currentFinishedActivity">
        <div style="margin-bottom: 12px;"><b>活动名称：</b>{{ currentFinishedActivity.title }}</div>
        <div style="margin-bottom: 12px;"><b>内容：</b>{{ currentFinishedActivity.content }}</div>
        <div style="margin-bottom: 12px;"><b>地点：</b>{{ currentFinishedActivity.location }}</div>
        <div style="margin-bottom: 12px;"><b>时间：</b>{{ currentFinishedActivity.startTime }} ~ {{ currentFinishedActivity.endTime }}</div>
        <div style="margin-bottom: 12px;"><b>状态：</b>{{ currentFinishedActivity.status }}</div>
        <el-form :model="evaluateForm" label-width="60px">
          <el-form-item label="评分">
            <el-rate v-model="evaluateForm.score" :max="5" />
          </el-form-item>
          <el-form-item label="评论">
            <el-input v-model="evaluateForm.evaluation" type="textarea" :rows="3" placeholder="请输入评价内容" />
          </el-form-item>
        </el-form>
        <div style="text-align:right;">
          <el-button type="primary" @click="handleEvaluate" :loading="evaluateLoading">提交评价</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
// 引入Vue相关API和依赖
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 获取当前学生ID
const stuId = localStorage.getItem('loginId')

// 活动总分
const totalPoints = ref(0)
// 未完成活动列表
const unfinishedActivities = ref([])
// 已完成活动列表
const finishedActivities = ref([])

// 签到/签退弹窗相关
const dialogVisible = ref(false)
const currentActivity = ref(null)

// 评价弹窗相关
const evaluateDialogVisible = ref(false)
const currentFinishedActivity = ref(null)
const evaluateForm = ref({
  score: 0,
  evaluation: ''
})
const evaluateLoading = ref(false)

// 获取活动数据（总分、未完成、已完成）
const fetchActivities = async () => {
  try {
    // 获取总分
    const pointRes = await axios.get(`http://localhost:8080/student/${stuId}/getPoints`)
    if (pointRes.data && typeof pointRes.data.data === 'number') {
      totalPoints.value = pointRes.data.data
    } else {
      totalPoints.value = 0
    }
    // 获取未完成活动
    const unfinishedRes = await axios.get(`http://localhost:8080/student/${stuId}/getUnfinishedActivities`)
    if (unfinishedRes.data && Array.isArray(unfinishedRes.data.data)) {
      unfinishedActivities.value = unfinishedRes.data.data
    } else {
      unfinishedActivities.value = []
    }
    // 获取已完成活动
    const finishedRes = await axios.get(`http://localhost:8080/student/${stuId}/getActivities`)
    if (finishedRes.data && Array.isArray(finishedRes.data.data)) {
      finishedActivities.value = finishedRes.data.data
    } else {
      finishedActivities.value = []
    }
  } catch (e) {
    ElMessage.error('获取活动信息失败')
  }
}

// 点击未完成活动行，弹出签到/签退弹窗
const handleUnfinishedRowClick = (row) => {
  currentActivity.value = row
  dialogVisible.value = true
}

// 点击已完成活动行，弹出评价弹窗
const handleFinishedRowClick = (row) => {
  currentFinishedActivity.value = row
  evaluateForm.value.score = 0
  evaluateForm.value.evaluation = ''
  evaluateDialogVisible.value = true
}

// 签到
const handleSignIn = async (activityId) => {
  try {
    const res = await axios.post(
      `http://localhost:8080/student/${activityId}/signIn`,
      stuId,
      { headers: { 'Content-Type': 'application/json' } }
    )
    if (res.data && res.data.code === 200) {
      ElMessage.success('签到成功')
      dialogVisible.value = false
      fetchActivities()
    } else {
      ElMessage.error(res.data.msg || '签到失败')
    }
  } catch (e) {
    ElMessage.error('网络错误或服务器异常')
  }
}

// 签退
const handleSignOut = async (activityId) => {
  try {
    const res = await axios.post(
      `http://localhost:8080/student/${activityId}/signOut`,
      stuId,
      { headers: { 'Content-Type': 'application/json' } }
    )
    if (res.data && res.data.code === 200) {
      ElMessage.success('签退成功')
      dialogVisible.value = false
      fetchActivities()
    } else {
      ElMessage.error(res.data.msg || '签退失败')
    }
  } catch (e) {
    ElMessage.error('网络错误或服务器异常')
  }
}

// 提交评价
const handleEvaluate = async () => {
  if (!evaluateForm.value.score || !evaluateForm.value.evaluation) {
    ElMessage.warning('请填写评分和评论')
    return
  }
  evaluateLoading.value = true
  try {
    const res = await axios.post(
      `http://localhost:8080/student/${currentFinishedActivity.value.actId}/${evaluateForm.value.score}/${encodeURIComponent(evaluateForm.value.evaluation)}/evaluateActivity`,
      stuId,
      { headers: { 'Content-Type': 'application/json' } }
    )
    if (res.data && res.data.code === 200) {
      ElMessage.success('评价提交成功')
      evaluateDialogVisible.value = false
      fetchActivities()
    } else {
      ElMessage.error(res.data.msg || '评价提交失败')
    }
  } catch (e) {
    ElMessage.error('网络错误或服务器异常')
  } finally {
    evaluateLoading.value = false
  }
}

// 页面加载时获取活动数据
onMounted(fetchActivities)
</script>